package com.basic.demo.controller;

import com.alibaba.fastjson.JSON;
import com.basic.demo.exception.BusinessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

@ControllerAdvice
public class testControllerAdvice {

    @ExceptionHandler
    public ModelAndView exceptionHandler(Exception ex){
        ModelAndView mv = new ModelAndView("error");
        mv.addObject("exception", ex);
        System.out.println("in testControllerAdvice");
        return mv;
    }

/*    @ExceptionHandler(value = BusinessException.class)
    public @ResponseBody  Map<String,Object> exceptionHandlerMap(Exception ex) {
        Map<String,Object> map = new TreeMap<String, Object>();
        map.put("status","success");
        return map;
    }*/


    /**
     * 返回JSON数据
     * @param e
     * @param request
     * @param response
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public void handleSimpleException(BusinessException e, final HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> map = new TreeMap<String, Object>();
        map.put("status", "success");
        map.put("message", "这是一个Json例子");
        try {
            response.getWriter().write(JSON.toJSONString(map));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

}